package com.innovation.chengzhangriji.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.innovation.chengzhangriji.Baby;
import com.innovation.chengzhangriji.BabyAndParent;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.Parent;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.BabyAddRequestBody;
import com.innovation.chengzhangriji.http.BabyAllResponse;
import com.innovation.chengzhangriji.http.Change;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.widget.CuteButton;
import com.innovation.chengzhangriji.ui.widget.CuteTextView;
import com.innovation.chengzhangriji.ui.widget.CuteToolbar;
import com.innovation.chengzhangriji.util.ChZhRJUtils;
import com.innovation.chengzhangriji.util.FileUtils;
import com.makeramen.roundedimageview.RoundedImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;

public class BabyNoticeDetailNotadminActivity extends BaseActivity implements CuteToolbar.OnClickCuteToolbarListener {
    private boolean delete,isnotice;
    private CuteTextView tv_name,tv_phone,tv_join_time,tv_shenfen,tv_nikename;
    private RoundedImageView imageView_head;
    private CuteToolbar toolbar;
    private String info,range,permission,mOldRole;
    private DisplayImageOptions options;
    private CuteButton btnCancel;
    private int role=-1,myrole=-1,myper=-1,myneirong=-1;
    private ImageView iv_shenfen_next,iv_quanxian_next,iv_neirong_next;
    private LinearLayout tv_notice_detail_relation_noadmin,noadmin_phonenumber;
    private BabyAllResponse babyAllResponse;
    private boolean b_quanxian = true,b_shenfen= true,b_neirong=true;

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1:
                    tv_name.setText(data.getStringExtra("relationship"));
                    break;
            }
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_baby_notice_detail_notadmin);
        toolbar = (CuteToolbar) findViewById(R.id.babynotice_detail_toolbar);
        toolbar.setOnClickCuteToolbarListener(this);
        tv_nikename= (CuteTextView) findViewById(R.id.tv_nikename);
        noadmin_phonenumber = (LinearLayout) findViewById(R.id.noadmin_phonenumber);
        tv_notice_detail_relation_noadmin = (LinearLayout) findViewById(R.id.tv_notice_detail_relation_noadmin);
        tv_notice_detail_relation_noadmin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BabyNoticeDetailNotadminActivity.this,PetnameListActivity.class);
                intent.putExtra("type","relationship");
                intent.putExtra("relationship",tv_name.getText().toString());
                startActivityForResult(intent,1);
            }
        });
        tv_name = (CuteTextView) findViewById(R.id.tv_chengwei_and_nikename_noadmin);
        tv_phone = (CuteTextView) findViewById(R.id.tv_notice_detail_phone_noadmin);
        tv_join_time = (CuteTextView) findViewById(R.id.tv_join_time_noadmin);
        tv_shenfen = (CuteTextView) findViewById(R.id.tv_shenfen_noadmin);

        imageView_head = (RoundedImageView) findViewById(R.id.iv_head_baby_notice_detail_noadmin);
        init();
    }

    private void init(){
        Intent intent = getIntent();
        permission = getIntent().getStringExtra("permission");
        babyAllResponse = get(permission, BabyAllResponse.class);
        if (babyAllResponse == null) {
            return;
        }
        toolbar.setCuteTitle(babyAllResponse.getName());
        tv_name.setText(babyAllResponse.getName());
        tv_phone.setText(babyAllResponse.getPhone());
        tv_nikename.setText("昵称：" + ChZhRJUtils.getText(babyAllResponse.getNickName(), ""));

        myrole = role = babyAllResponse.getAuth().getRole();
        myper  = babyAllResponse.getAuth().getPermission();
        myneirong  = babyAllResponse.getAuth().getRange();

        final LoginInfo login = Config.getLoginInfo(BabyNoticeDetailNotadminActivity.this);
        if (login == null) {
            return;
        }
        String phone = mLoginInfo.getPhone();
        if (!phone.equals(babyAllResponse.getPhone())){
            noadmin_phonenumber.setVisibility(View.GONE);
            tv_notice_detail_relation_noadmin.setVisibility(View.GONE);
        }

        role = babyAllResponse.getAuth().getRole();
        switch (role){
            case 2:
                tv_shenfen.setText("大家长");
                break;
            case 1:
                tv_shenfen.setText("家长");
                break;
            case 0:
                tv_shenfen.setText("成员");
                break;
        }
        String type = null;
        switch (babyAllResponse.getType()) {
            case 1:
                type = "创建日记";
                break;
            case 2:
                type = "由" + babyAllResponse.getUser() + "邀请加入";
                break;
            case 3:
                type = "由" + babyAllResponse.getUser() + "批准加入";
                break;
        }

        tv_join_time.setText(babyAllResponse.getServerTS() + "\u2000" + babyAllResponse.getMessage());

        info = getIntent().getStringExtra("info");

        setOptions();
        ImageLoader.getInstance().displayImage(babyAllResponse.getPath(), imageView_head, options);
    }
    private void babyUpload() {
        final LoginInfo login = Config.getLoginInfo(BabyNoticeDetailNotadminActivity.this);
        Log.e("asd", "" + login);
        if (login == null) {
            return;
        }
        String userId = mLoginInfo.getUserID();
        String phone = mLoginInfo.getPhone();
        String token = mLoginInfo.getToken().getAccessToken();
        final BabyAddRequestBody body = new BabyAddRequestBody();
        final int babyId = mLoginInfo.getBabyID();
        body.setParentName(tv_name.getText().toString());
        mOldRole =  tv_name.getText().toString();
        final Baby babys = DatabaseManager.getInstance(BabyNoticeDetailNotadminActivity.this).queryBaby(userId, babyId);
        Change[] mChanges = new Change[1];
        mChanges[0] = new Change();
        mChanges[0].setKey("UserMemberName");
        mChanges[0].setValue(tv_name.getText().toString());
        Client.requestBabyUpdate(this, phone, token, babyId, System.currentTimeMillis(),mChanges, new ResponseHandler() {

            @Override
            public void onInnovationStart() {
                showProgressDialog(null, null);
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                babys.setParentName(tv_name.getText().toString());

                updateBaby(babys);
                updateTimeline(babys.getBabyID(), babys.getParentName());
                dismissProgressDialog();
//                setResult(Activity.RESULT_OK);
                finish();
            }

            @Override
            public void onChZhRJFailure(String value) {
                dismissProgressDialog();
                tipShow(value);
            }

            @Override
            public void onChZhRJTokenFailure(String value) {
                dismissProgressDialog();
                tipShow(value);
                finish();
            }
        }, networkUnavailableSampleImpl());
    }
    public void updateBaby(Baby baby) {
        DatabaseManager.getInstance(this).updateBaby(baby);
    }
    public void updateTimeline(int babyID, String newRole) {
        if (mOldRole.equals(newRole)) {
            return;
        }
        DatabaseManager.getInstance(this).updateRole(babyID, mOldRole, newRole);
    }

    private void setOptions() {
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.ic_head_circle_default_small)    //在ImageView加载过程中显示图片
                .showImageForEmptyUri(R.drawable.ic_head_circle_default_small)  //image连接地址为空时
                .showImageOnFail(R.drawable.ic_head_circle_default_small)  //image加载失败
                .cacheOnDisk(true)   //加载图片时会在磁盘中加载缓存
                .build();
    }
    //    private void sendDeleteBroadcast() {
//        Intent intent = new Intent("delete");
//        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
//    }
    private void updateDb(){
        final LoginInfo loginInfo = Config.getLoginInfo(this);
        final String userId = loginInfo.getUserID();
        final String phone = loginInfo.getPhone();
        final String token = loginInfo.getToken().getAccessToken();
        final  int babyId = loginInfo.getBabyID();
        Client.requestBabyAll(BabyNoticeDetailNotadminActivity.this, phone, token, babyId, new ResponseHandler() {

            @Override
            public void onInnovationSuccess(JsonElement value) {
                super.onInnovationSuccess(value);
                JsonObject object = value.getAsJsonObject();
                JsonArray jsonArray = object.getAsJsonArray("Messages");
                BabyAllResponse[] responses = get(jsonArray.toString(), BabyAllResponse[].class);
                if (responses == null) {
                    return;
                }
                Parent[] parents = new Parent[responses.length];
                for (int i = 0; i < responses.length; i++) {
                    parents[i] = new Parent();
                    parents[i].setBabyId(babyId);
                    parents[i].setType(responses[i].getType());
                    parents[i].setParentId(responses[i].getUserId());
                    parents[i].setUser(responses[i].getUser());
                    parents[i].setName(responses[i].getName());
                    parents[i].setPhone(responses[i].getPhone());
                    parents[i].setServerTS(responses[i].getServerTS());
                    parents[i].setMessage(responses[i].getMessage());
                    parents[i].setPath(responses[i].getPath());
                    parents[i].setNickName(responses[i].getNickName());
                    parents[i].setRole(responses[i].getAuth().getRole());
                    parents[i].setPermission(responses[i].getAuth().getPermission());
                    parents[i].setRange(responses[i].getAuth().getRange());
                }
                DatabaseManager.getInstance(BabyNoticeDetailNotadminActivity.this).deleteAllParents(babyId);
                DatabaseManager.getInstance(BabyNoticeDetailNotadminActivity.this).insertOrReplaceInTxParent(parents);
                finish();
            }

        }, networkUnavailableSampleImpl());
    }
    @Override
    public void onClickLeft() {
        if (babyAllResponse.getAuth().getRole() == myrole && babyAllResponse.getAuth().getPermission() == myper
                && babyAllResponse.getAuth().getRange() == myneirong && babyAllResponse.getName().equals(tv_name.getText().toString())) {
            onBackPressed();
        }if (babyAllResponse.getAuth().getRole() == myrole && babyAllResponse.getAuth().getPermission() == myper
                && babyAllResponse.getAuth().getRange() == myneirong && !babyAllResponse.getName().equals(tv_name.getText().toString())){
            babyUpload();
        }
    }

    @Override
    public void onClickRight() {

    }
}
